// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EventCommandDispatcher.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the EventCommandDispatcher type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Windows.Input.Commands
{
    using System;
    using System.Reflection;
    using System.Windows;
    using Photon;

    public abstract class EventCommandDispatcher<T> : CommandDispatcher<T> where T : UIElement
    {
        #region Fields

        private Delegate _handler;

        #endregion

        protected abstract IEventBinder EventBinder { get; }

        protected Delegate Handler
        {
            get
            {
                return this._handler ?? (this._handler = Delegate.CreateDelegate(this.EventBinder.EventType, this,
                    GetType().GetMethod("OnInvoke", BindingFlags.NonPublic | BindingFlags.Instance)));
            }
        }

        protected override void OnTargetChanged(T oldValue, T newValue)
        {
            if (oldValue != null)
            {
                this.EventBinder.Remove(oldValue, null, this.Handler);
            }

            if (newValue != null)
            {
                this.EventBinder.Add(newValue, this.Handler);
            }
        }
    }
}